package com.captain.leetcode.链表;

/**
 * Des:
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 *
 * @author XL
 * @Date 2021/7/31 15:43
 */
public class 旋转链表61 {

    public static void main(String[] args) {
        new 旋转链表61().rotateRight(ListNode.getInstance(), 1);

    }

    public ListNode rotateRight(ListNode head, int k) {

        //4 - 1 - 2 - 3 - 4
        if (head == null || head.next == null) {
            return head;
        }
        int len = 1, index;
        ListNode temp = head, newHead;
        //计算链表长度len,循环链表
        while (temp.next != null) {
            len++;
            temp = temp.next;
        }
        temp.next = head;
        if (k >= len) {
            return head;
        }
        index = len - k;
        while (index-- > 0) {
            temp = temp.next;
        }
        //新的开始节点
        newHead = temp.next;
        //断开循环链表
        temp.next = null;
        return newHead;
    }
}
